<template>
  <div class="new_div1 display">
    <el-dialog
      v-model="dialogVisibles"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :destroy-on-close="true"
      @close = "share_cancel(form_new_date)"
      width="80%"
    >
      <template #header>
        <div class="customerTitle2">订单信息<span class="title1">{{copyList && copyList?.type == 1 && copyList.uid || ''}}</span></div>
      </template>
      <div class="divColor" >
        <div class="new_font1">
          <div class="titleDiv"/>
          <div>
            基本信息
          </div>
        </div>
        <div>
          <el-form
            label-width="105px"
            ref="form_new_date"
            :model="form_new_list"
            :rules="rules"
          >
            <el-row :gutter="24">
              <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
                <el-form-item label="客户" prop="customer_uid">
                  <VabSelectForm @change='customerChange' :clearable="false" v-model="form_new_list.customer_uid" :options="customer_list"/>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
                <el-form-item label="销售组织" prop="sales_org_id">
                  <VabSelectForm @change="changeSelect"  :clearable="false"  v-model="form_new_list.sales_org_id" :options="sales_org_list"/>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
                <el-form-item label="价目表" prop="price_list_uid">
                  <el-select
                    filterable
                    v-model="form_new_list.price_list_uid"
                    class="width_100"
                    placeholder="请选择"
                    @change="priceChange"
                  >
                    <el-option v-for="item in price_list" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
                <el-form-item label="寄售仓库" prop="consignment_warehouse_no">
                  <el-select
                    filterable
                    v-model="form_new_list.consignment_warehouse_no"
                    class="width_100"
                    placeholder="请选择"
                    @change="consignmentWarehouseChang(form_new_list.consignment_warehouse_no)"
                  >
                    <el-option v-for="item in consignmentWarehouseList" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
                <el-form-item label="期望运输方式" prop="transport_type">
                  <el-select
                    filterable
                    v-model="form_new_list.transport_type"
                    class="width_100"
                    placeholder="请选择"
                  >
                    <el-option v-for="item in transport_type_list" :key="item.value"  :label="item.label" :value="item.value">
                      <span style="float: left" >{{ item.label }}</span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
                <el-form-item label="联系人" prop="contact_user">
                  <el-input
                    v-model="form_new_list.contact_user"
                  />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
                <el-form-item label="联系电话" prop="contact_tel">
                  <el-input
                    v-model="form_new_list.contact_tel"
                  />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="16" :md="16" :lg="16" :xl="16" style="padding-right: 0px">
                <el-form-item label="收货地址" prop="shipping_address" style="width: 100%;display: flex;justify-content: space-between" >
                  <el-cascader
                    ref="address_ref"
                    v-model="form_new_list.shipping_address"
                    :options="areaOption"
                    style="width:42%;display: inline-block"
                    :props="{ value: 'name', label: 'name' }"
                  >
                    <template #default="{ data }">
                      <span>{{ data.name }}</span>
                    </template>
                  </el-cascader>
                  <el-input
                    v-model="form_new_list.address"
                    class="inputAddress"
                    style="width: calc(57% - 15px) "
                    placeholder="详细地址"
                  >
                    <template #append >
                      <!--                    <span @click="openAddress" >
                                            地址簿
                                          </span>-->
                      <el-button size="small" @click="openAddress" >地址簿 </el-button>
                    </template>
                  </el-input>
                  <!--                <el-button style="width: 100%" size="small" type="primary" @click="openAddress" >地址簿 </el-button>-->
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
                <el-form-item label="运费付款方式" prop="payment_type">
                  <VabSelectForm  :clearable="false" v-model="form_new_list.payment_type" :options="payment_type_list"/>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
                <el-form-item label="期望送达时间" prop="delivery_time">
                  <el-date-picker
                    v-model="form_new_list.delivery_time"
                    type="date"
                    :clearable="false"
                    style="width: 100%"
                    placeholder="请选择时间"
                  />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
                <el-form-item label="结算币别" prop="trading_curr_id">
                  <VabSelectForm :clearable="false"  v-model="form_new_list.trading_curr_id" :options="currency"/>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
                <el-form-item label="开票类型" prop="invoice_type">
                  <VabSelectForm :clearable="false"  v-model="form_new_list.invoice_type" :options="invoice_type_list"/>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="16" :xl="8">
                <el-form-item label="备注" prop="remark">
                  <el-input
                    v-model="form_new_list.remark"
                    autosize
                    type="textarea"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
      <div class="divColor" style="margin-top: 20px;padding-bottom: 10px">
        <ConsignProducts ref="products_ref" v-model:copyProductList="copyProductList" v-model:copyProductNumber="copyProductNumber" />
      </div>
      <template #footer>
        <span class="dialog-footer customerDialog3">
            <el-button @click="share_cancel(form_new_date)">取消</el-button>
          <el-button type="primary"  @click="share_save(form_new_date)">提交</el-button>
        </span>
      </template>
    </el-dialog>
    <Address ref="addressSon" />
  </div>
</template>

<script setup lang="ts">
import {ref} from "vue";
import {ElMessage, ElMessageBox, FormRules} from "element-plus";
import {areaOptions} from "/@/views/corpManagement/corpCustomers/tools";
import ConsignProducts from './ConsignProducts.vue'
import lodash from 'lodash';
import Address from '../../component/Address.vue'
import {customer_info, customer_optionsList, customerPriceList} from "/@/api/dms/customer";
import {organization_list} from "/@/api/dms/organization";
import {options_list, optionsCreate} from "/@/api/dms/options";
import {orderInsert} from "/@/api/dms/order";
import { flattenArray, productFields } from "/@/views/order_management/orderText";
import { DateFormat } from "/@/utils/utils";
import { getInventoryConsginStockList } from "/@/api/dms/inventory";
defineOptions({
  name: 'NewOrder',
})
const dialogVisibles = ref(false)
//按钮加载
const buttonLoading = ref(false)
const form_new_date = ref<any>(null)
// 获取组
const getGroupList = ref<any>(undefined)
// 获取列表信息 复制使用
const copyList = ref<any>(undefined)
//复制数据暂存
const copyProductList = ref(undefined)
// 复制总数数据
const copyProductNumber = ref<any>(undefined)
const customerNumber = ref<any>(undefined)
// 判断 是否为提交关闭窗口
const submit = ref(false)
const form_new_list = ref<any>({
  customer_name:'',
  //客户id
  customer_uid:'',
  //客户编码
  customer_number:'',
  // 价目表
  price_list_uid:'',
  // 折扣表
  discount_uid:'',
  //运输方式
  transport_type:'',
  //费用结算方式
  payment_type:'',
  //备注
  remark:'',
  //联系信息
  contact_user:'',
  contact_tel:'',
  //销售组织
  sales_org_id:'',
  //收货地址
  shipping_address:'',
  address:'',
  //币别
  trading_curr_id:'',
  // 开票类型
  invoice_type:'',
  consignment_warehouse_no:'',////寄售出库
  delivery_time:'',//期待送达时间
})
const rules = ref<FormRules<any>>({
  contact_user: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
  contact_tel: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
  shipping_address: [{ required: true, message: '请选择收货地址', trigger: 'change' }],
  transport_type: [{ required: true, message: '请选择运输方式', trigger: 'change' }],
  payment_type: [{ required: true, message: '请选择费用结算方式', trigger: 'change' }],
  price_list_uid: [{ required: true, message: '请选择价目表', trigger: 'change' }],
  sales_org_id: [{ required: true, message: '请选择销售组织', trigger: 'change' }],
  customer_uid: [{ required: true, message: '请选择客户', trigger: 'change' }],
  trading_curr_id: [{ required: true, message: '请选择币别', trigger: 'change' }],
  invoice_type: [{ required: true, message: '请选择开票类型', trigger: 'change' }],
  consignment_warehouse_no:[{ required: true, message: '请选择寄售仓库', trigger: 'change' }],////寄售仓库
  // delivery_time:[{ required: true, message: '请选择期待送达时间', trigger: 'change' }],//期待送达时间
})
// **********选择框的内容***********
const customer_list = ref([])
let price_list  = ref<any>([])
const discount_list = ref([{value:'折扣表',label:'折扣表'}])
const sales_org_list = ref([])
const transport_type_list = ref<any>([])
const payment_type_list =ref([{value:'1',label:'运费到付'},{value:'2',label:'运费预付'}])
//寄售仓库
const consignmentWarehouseList = ref<any>([])
// 地址
const address_ref =ref<any>(null)
const areaOption = ref<any>([])
// 财务信息
let currency = ref([])
let invoice_type_list = ref([])
// ******地址簿*******
const addressSon =ref<any>({})
const openAddress = ()=>{
  if(form_new_list.value.customer_uid != '' && form_new_list.value.customer_uid ){
    addressSon.value.dialogVisibles = true
    addressSon.value.customerId = form_new_list.value.customer_uid
    addressSon.value.selectAddress = undefined
  }else {
    ElMessage.warning(`客户不能为空，请先选择客户`)
  }

}
const transport = (va:any)=>{
  ElMessageBox.prompt(' ', '添加运输方式', {
    confirmButtonText: '提交',
    cancelButtonText: '取消',
    center: true,
    /*inputPattern:
      /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,*/
    inputErrorMessage: 'Invalid Email',
  })
    .then(({ value }) => {
      optionsCreate({label:value.trim(),level:2,module:'transport_type',module_name:'运输方式',sort:50}).then((data:any)=>{
        if(data.code == 200){
          options_list({module:'transport_type',level:2}).then((data:any)=>{
            if(data.code == 200){
              ElMessage.success(`提交成功`)
              const arr = data.data.map((item:any)=> {return {value:item.uid , label:item.name}})
              transport_type_list.value = arr
            }
          })
        }
      })
    })
}
// *****表单客户更改********
const customerChange = (value:any)=>{
  const data:any = customer_list.value?.filter((item:any)=>{return item.value == value})[0]
  customerNumber.value= data.number
  customer_info({uid:value}).then((data:any)=>{
    const getAddress = data.data.location?.filter((i:any)=>i.is_default_consignee == 1)[0] || undefined
    form_new_list.value = {
      ...form_new_list.value,
      // 价目表
      price_list_uid:'',
      // 折扣表
      discount_uid:'',
      //运输方式
      transport_type:'',
      //费用结算方式
      payment_type:'',
      //备注
      remark:'',
      //联系信息
      contact_user:getAddress && getAddress.shipping_contact || '',
      contact_tel:getAddress && getAddress.shipping_tel || '',
      //销售组织
      sales_org_id:'',
      //收货地址
      shipping_address:getAddress && getAddress.shipping_address.split(",") || '',
      address:getAddress && getAddress.address || '',
      //币别
      trading_curr_id:data.data.trading_curr_id || '',
      // 开票类型
      invoice_type:data.data.invoice_type || ''
    }
  })
  copyProductNumber.value = form_new_list.value
  products_ref.value.productList = [productFields]
}
//****** 产品信息**********
const products_ref=ref<any>(undefined)
// *********按钮***************
const check = ()=>{
  const product_list = flattenArray(products_ref.value.productList)
  const  check1 =  product_list.map((item:any,index:any)=>{
    if(item.goods_no == '' || item.goods_no == undefined){
      ElMessage.warning(`序号为 ${index +1}产品编码 不能为空`)
      return false
    }else {
      return true
    }
  })
  const  check2 =  product_list.map((item:any,index:any)=>{
    if(item.goods_name == '' || item.goods_name == undefined){
      ElMessage.warning(`序号为 ${index +1}产品名称 不能为空`)
      return false
    }else {
      return true
    }
  })
  const  check3 =  product_list.map((item:any,index:any)=>{
    if(item.goods_type == '' || item.goods_type == undefined){
      ElMessage.warning(`序号为 ${index +1}产品类型 不能为空`)
      return false
    }else {
      return true
    }
  })
  const  check4 =  product_list.map((item:any,index:any)=>{
    if(item.sales_num == '' || item.sales_num == undefined || item.sales_num == 0){
      ElMessage.warning(`序号为 ${index +1}销售数量 不能为0`)
      return false
    }else {
      if( item.batch_usable_num < item.sales_num ){
        ElMessage.warning(`序号为 ${index +1}预计可发量 小于 销售数量`)
        return false
      }else {
        return true
      }

    }
  })
  const  check5 =  product_list.map((item:any,index:any)=>{
    if(item.warehouse_no == '' || item.warehouse_no == undefined){
      ElMessage.warning(`序号为 ${index +1}仓库 不能为空`)
      return false
    }else {
      return true
    }
  })
  const  check8 =  product_list.map((item:any,index:any)=>{
    if(item.tax_rate == '' || item.tax_rate == undefined){
      ElMessage.warning(`序号为 ${index +1}税率 不能为空`)
      return false
    }else {
      return true
    }
  })
  const  check9 =  product_list.map((item:any,index:any)=>{
    if(item.sales_unit == '' || item.sales_unit == undefined){
      ElMessage.warning(`序号为 ${index +1}销售单位 不能为空`)
      return false
    }else {
      return true
    }
  })
  const  check7 =  product_list.map((item:any,index:any)=>{
    if(item.goods_type !== '赠品'&& item.goods_type !== '样品'){
      if( item.order_price == '' || item.order_price == 0){
        ElMessage.warning(`序号为 ${index +1}含税单价 不能为空`)
        return false
      }else if(item.including_tax_price  != item.price ){
        if(item.price_remark =='' || item.price_remark == undefined){
          ElMessage.warning(`序号为 ${index +1}改价原因 不能为空`)
          return false
        }else {
          return true
        }
      }else {
        return true
      }
    }else {
      return true
    }
  })
  const check6 = [...check1,...check2,...check3,...check4,...check5,...check8,...check9,...check7].every(i=>i==true)
  return check6
}
const share_save = lodash.debounce( async (va:any)=>{
  console.log(form_new_list.value.delivery_time,999);
  buttonLoading.value = true
  const product_list = flattenArray(products_ref.value.productList)
  const product_many = products_ref.value.products_number?.reduce((obj:any, item:any) => {
    obj[item.item] = item.value;
    return obj;
  }, {})
  const product_check = check()
  await va.validate((valid: any, fields: any) => {
    if (valid) {
      if(product_check) {
        orderInsert({...form_new_list.value,delivery_time:form_new_list.value.delivery_time ==''? '' :DateFormat(form_new_list.value.delivery_time, 'YYYY-MM-DD'),consignment_warehouse_name:consignmentWarehouseName(form_new_list.value.consignment_warehouse_no),shipping_address:form_new_list.value.shipping_address.toString(),...product_many,trade_from:'员工',detail:[...product_list],order_group_uid:getGroupList.value.uid}).then((data:any)=>{
          if(data.code == 200){
            ElMessage.success(`提交成功`)
            va.resetFields()
            products_ref.value.productList =[]
            products_ref.value.products_number = []
            submit.value =true
            dialogVisibles.value= false
            copyList.value=undefined
            customerNumber.value = undefined
            addressSon.value.selectAddress= []
          }
          buttonLoading.value = false
        })
      }
    }
  })
},500)
const share_cancel = (formEl:any)=>{
  formEl.resetFields()
  customerNumber.value = undefined
  products_ref.value.productList =[]
  products_ref.value.products_number = []
  dialogVisibles.value= false
  copyList.value=undefined
  addressSon.value.selectAddress= []
}
//获取客户
const getCustomer=async ()=>{
  // 客户
  await customer_optionsList({is_group:2,name:''}).then((data:any)=>{
    if(data.code == 200){
      customer_list.value = data.data.map((item:any)=> {return {value:item.uid, label:item.name,number:item.number}})
    }
  })
  // 组织
  await  organization_list({}).then((data:any)=>{
    if(data.code == 200){
      sales_org_list.value = data.data.map((item:any)=> {return {value:item.uid , label:item.name}})
    }
  })
  // 运输方式
  await options_list({module:'transport_type',level:2}).then((data:any)=>{
    if(data.code == 200){
      const arr = data.data.map((item:any)=> {return {value:item.uid , label:item.name}})
      //[...arr,{value:-1 , label:'自定义',display:true}]
      transport_type_list.value = arr
    }
  })
  options_list({module:'currency'}).then((data:any)=>{
    // console.log(data,'币别')
    if(data.code == 200){
      currency.value = data.data?.map((i:any)=>{return {value:i.uid,label:i.name}}) || []
    }else {
      currency.value=[]
    }
  })
  options_list({module:'invoice_type'}).then((data:any)=>{
    // console.log(data,'币别')
    if(data.code == 200){
      invoice_type_list.value = data.data?.map((i:any)=>{return {value:i.uid,label:i.name}}) || []
    }else {
      invoice_type_list.value=[]
    }
  })
  // 寄售订单
  getInventoryConsginStockList({}).then((data:any)=>{
    if(data.code == 200){
      consignmentWarehouseList.value = data.data.list.map((va:any)=>{return {value:va.key,label:va.label}})
    }
  })
}
//获取下拉框值
const changeSelect =(va:string,value:any)=>{
  form_new_list.value = {
    ...form_new_list.value,
    // 价目表
    price_list_uid:'',
  }
  copyProductNumber.value =  {
    ...form_new_list.value,
    // 价目表
    price_list_uid:'',
  }
  const data:any = customer_list.value?.filter((item:any)=>{return item.value ==  form_new_list.value.customer_uid})[0]
  customerNumber.value= data.number
  products_ref.value.productList = [productFields]
}
//价目表下拉框
const priceChange = ()=>{
  copyProductNumber.value = form_new_list.value
  products_ref.value.productList = [productFields]
}
// 获取寄售仓库
const consignmentWarehouseName = (value:any)=>{
  if(value){
    return  consignmentWarehouseList.value?.filter((va:any)=> va.value == value)[0]?.label || ''
  }else {
    return ''
  }

}
const consignmentWarehouseChang = (value:any)=>{
  copyProductNumber.value = form_new_list.value
}
// 监听
watchEffect(()=>{
  const {selectAddress} = addressSon.value  || []
  if(selectAddress && selectAddress.length > 0 ){
    form_new_list.value.contact_user= selectAddress[0].shipping_contact,
      form_new_list.value.contact_tel =  selectAddress[0].shipping_tel
    form_new_list.value.shipping_address = selectAddress[0].shipping_address,
      form_new_list.value.address = selectAddress[0].address
  }
  if(customerNumber.value && form_new_list.value.sales_org_id != ''){
    customerPriceList({page:1,limit:1000,type:2,filter:{use_org_id:form_new_list.value.sales_org_id,customer_number:customerNumber.value}}).then((data:any)=>{
      if(data.code == 200){
        price_list.value = data.data.list.map((i:any)=>{return {value:i.id,label:i.name}})
      }
    })
  }else {
    price_list.value = []
  }
})
watch(copyList,()=>{
  if(copyList.value){
    const data:any = customer_list.value?.filter((item:any)=>{return item.value == copyList.value.customer_uid})[0]
    customerPriceList({page:1,limit:1000,type:2,filter:{use_org_id:copyList.value.sales_org_id,customer_number:data.number}}).then((data:any)=>{
      if(data.code == 200){
        price_list.value = data.data.list.map((i:any)=>{return {value:i.id,label:i.name}})
      }
    })
    if(copyList.value?.type == 1){
      form_new_list.value = {
        consignment_warehouse_no:copyList.value.consignment_warehouse_no,
        delivery_time:copyList.value.delivery_time,
        trading_curr_id:copyList.value.trading_curr_id,
        invoice_type:copyList.value.invoice_type,
        address:copyList.value.address,
        sales_org_id:copyList.value.sales_org_id,
        contact_tel:copyList.value.contact_tel,
        contact_user:copyList.value.contact_user,
        remark:copyList.value.remark,
        customer_uid:copyList.value.customer_uid,
        price_list_uid:Number(copyList.value.price_list_uid),
        discount_uid:copyList.value.discount_uid,
        transport_type:copyList.value.transport_type,
        payment_type:copyList.value.payment_type,
        shipping_address:copyList.value && copyList.value.shipping_address.split(",") || [],
        uid:copyList.value.uid}
      copyProductList.value = copyList.value && copyList.value.detail || undefined
      copyProductNumber.value = copyList.value
    }else if(copyList.value?.type == 2) {
      form_new_list.value = {
        consignment_warehouse_no:copyList.value.consignment_warehouse_no,
        delivery_time:copyList.value.delivery_time,
        trading_curr_id:copyList.value.trading_curr_id,
        invoice_type:copyList.value.invoice_type,
        address:copyList.value.address,
        sales_org_id:copyList.value.sales_org_id,
        contact_tel:copyList.value.contact_tel,
        contact_user:copyList.value.contact_user,
        remark:copyList.value.remark,
        customer_uid:copyList.value.customer_uid,
        price_list_uid:Number(copyList.value.price_list_uid),
        discount_uid:copyList.value.discount_uid,
        transport_type:copyList.value.transport_type,
        payment_type:copyList.value.payment_type,
        shipping_address:copyList.value && copyList.value.shipping_address.split(",") || []}
      copyProductList.value = copyList.value && copyList.value.detail || undefined
      copyProductNumber.value = copyList.value
    }
  }else {
    form_new_list.value = {
      consignment_warehouse_no:'',
      delivery_time:'',
      trading_curr_id:'',
      invoice_type:'',
      address:'',
      sales_org_id:'',
      contact_tel:'',
      contact_user:'',
      remark:'',
      customer_uid:'',
      price_list_uid:'',
      discount_uid:'',
      transport_type:'',
      payment_type:'',
      shipping_address: []}
    copyProductList.value = undefined
    copyProductNumber.value = undefined
  }

})
defineExpose(
  {
    dialogVisibles,
    getGroupList,
    submit,
    copyList,
  }
)
onMounted(async ()=>{
  // 获取地址
  areaOption.value = await areaOptions()
  //获取客户
  getCustomer()
})
</script>

<style lang="scss" scoped>
@import "../../index";
.constItem{
  :deep(){
    .el-form-item{
      margin-bottom: 2px;
    }
  }
  .button{
    width: 100%;
    display: flex;
    justify-content: flex-end;
    margin-bottom: 2px;
  }
}
.border{
  margin-bottom: 10px;
  border-top: 1px solid #bdbdbd;
  border-radius: 0px;
}
.inputAddress{
  margin-left:10px;
  margin-right:10px;
  :deep(){
    .el-input__wrapper{
      width: 100%;
    }
    .el-input-group__append{
      background-color:var(--el-color-primary);
      color: #fff;
      box-shadow: 0 0px 0 0var(--el-color-primary)
    }
  }
}
</style>

